<template>
  <!-- 转运申请 -->
  <view class="add-risk">
    <uni-forms v-model="formData" ref="form" validateTrigger="bind" @submit="submit">
      <uni-forms-item v-for="(item, index) in quarantineInfo" v-if="item.type" :key="index" :label="item.label" :name="item.name" :required="item.required" labelWidth="85" class="no-border" :en="item.english">

        <input v-if="item.type === 'input'" :placeholder="item.placeholder" :value="formData[item.name]" @blur="binddata(item.name, $event.detail.value)" />

        <textarea v-if="item.type === 'textarea'" :maxlength="-1" :placeholder="item.placeholder" :value="formData[item.name]" @blur="binddata(item.name, $event.detail.value)" />

        <picker 
          v-if="item.type === 'date'"
          mode="date" 
          :value="formData[item.name]"
          :start="item.startDate" 
          :end="item.endDate" 
          :placeholder="item.placeholder"
          @change="binddata(item.name, $event.detail.value)">
            <view class="inner">
              <text :class="{'uni-input': true, 'placeholder': !formData[item.name]}">{{ formData[item.name] || item.placeholder }}</text>
            </view>  
        </picker>

        <uni-datetime-picker
          v-if="item.type ==='datetime'"
          type="datetime"
          v-model="formData[item.name]"
        >
          <view class="inner">
            <text :class="{'uni-input': true, 'placeholder': !formData[item.name]}">{{ formData[item.name] || item.placeholder }}</text>
          </view>  
        </uni-datetime-picker>
        
        <picker 
          v-if="item.type === 'time'"
          mode="time" 
          :value="formData[item.name]"
          :start="item.startDate" 
          :end="item.endDate" 
          @change="binddata(item.name, $event.detail.value)">
           <view class="inner">
            <text :class="{'uni-input': true, 'placeholder': !formData[item.name]}">{{ formData[item.name] || item.placeholder }}</text>
          </view>
        </picker>

        <picker
          v-if="item.type ==='select'"
          @change="handleListChange($event, item.name, item.options, 'value')"
          :value="item.options.findIndex(e => e.value === formData[item.name])"
          range-key="label"
          :placeholder="item.placeholder"
          :range="item.options"
        >
          <view class="inner">
            <text :class="{'uni-input': true, 'placeholder': !matchLabel(item.options, formData[item.name])}">{{matchLabel(item.options, formData[item.name], item.placeholder)}}</text>
          </view>  
        </picker>

        <radio-group 
          v-if="item.type === 'radio'"
          @change="binddata(item.name, $event.detail.value)"
        >
          <label class="radio uni-list-cell uni-list-cell-pd" v-for="(radio, index) in item.options" :key="radio.value">
              <radio color="#2984F8" :value="String(radio.value)" :checked="formData[item.name] === String(radio.value)" />
              <text>{{radio.label}}</text>
          </label>
        </radio-group>

        <checkbox-group 
          v-if="item.type === 'checkbox'"
          @change="binddata(item.name, $event.detail.value)"
        >
            <label class="checkbox uni-list-cell uni-list-cell-pd" v-for="check in item.options" :key="check.value">
              <checkbox :value="String(check.value)" :checked="formData[item.name] === check.value" />
              <text>{{check.label}}</text>
            </label>
        </checkbox-group>

        <ld-select 
          v-if="item.type === 'multiselect'"
          :multiple="true" 
          :list="item.options"
          label-key="label" 
          value-key="value"
          :placeholder="item.placeholder"
          clearable
          :value="formData[item.name]"
          @change="handleMultiselectChange(item.name, arguments)"
          >
        </ld-select>

        <pick-regions 
          v-if="item.type === 'regions'"
          :defaultRegion="formData[item.name]" 
          :regions="(item.options && item.options.length) ? item.options : regions"
          @getRegion="handleGetRegion(item.name, arguments)">
            <text>{{formData[item.name] ? formData[item.name].join('-') : ''}}</text>
        </pick-regions>

        <!-- 身份证 -->
        <input v-if="item.type === 'idCard'" :placeholder="item.placeholder" :value="formData[item.name]" @blur="handleIdCardBlur(item.name, arguments)" />

        <!-- 出生日期 -->
        <picker v-if="item.type === 'birthday'" mode="date" :value="formData[item.name]" :start="startDate" :end="endDate" @change="handleBirthdayChange(item.name, arguments)">
          <view class="inner">
            <text :class="{'uni-input': true, 'placeholder': !formData[item.name]}">{{ formData[item.name] || item.placeholder }}</text>
          </view>
        </picker>

        <!-- 省 -->
        <picker
          v-if="item.type ==='province'"
          @change="handlePlaceChange(item.name, arguments, provinceOptions, ['city', 'county', 'street', 'village'], 'cityOptions', 'province')"
          :value="provinceOptions.findIndex(e => e.code === formData[item.name])"
          range-key="name"
          :placeholder="item.placeholder"
          :range="provinceOptions"
        >
          <view class="inner">
            <text :class="{'uni-input': true, 'placeholder': !matchName(provinceOptions, formData[item.name])}">{{matchName(provinceOptions, formData[item.name], item.placeholder)}}</text>
          </view>  
        </picker>

        <!-- 市 -->
        <picker
          v-if="item.type ==='city'"
          @change="handlePlaceChange(item.name, arguments, cityOptions, ['county', 'street', 'village'], 'countyOptions', 'city')"
          :value="cityOptions.findIndex(e => e.code === formData[item.name])"
          range-key="name"
          :placeholder="item.placeholder"
          :range="cityOptions"
        >
          <view class="inner">
            <text :class="{'uni-input': true, 'placeholder': !matchName(cityOptions, formData[item.name])}">{{matchName(cityOptions, formData[item.name], item.placeholder)}}</text>
          </view>  
        </picker>

        <!-- 县 -->
        <picker
          v-if="item.type ==='county'"
          @change="handlePlaceChange(item.name, arguments, countyOptions, ['street', 'village'], 'streetOptions', 'county')"
          :value="countyOptions.findIndex(e => e.code === formData[item.name])"
          range-key="name"
          :placeholder="item.placeholder"
          :range="countyOptions"
        >
          <view class="inner">
            <text :class="{'uni-input': true, 'placeholder': !matchName(countyOptions, formData[item.name])}">{{matchName(countyOptions, formData[item.name], item.placeholder)}}</text>
          </view>  
        </picker>

        <!-- 街道 -->
        <picker
          v-if="item.type ==='street'"
          @change="handlePlaceChange(item.name, arguments, streetOptions, ['village'], 'villageOptions', 'street')"
          :value="streetOptions.findIndex(e => e.code === formData[item.name])"
          range-key="name"
          :placeholder="item.placeholder"
          :range="streetOptions"
        >
          <view class="inner">
            <text :class="{'uni-input': true, 'placeholder': !matchName(streetOptions, formData[item.name])}">{{matchName(streetOptions, formData[item.name], item.placeholder)}}</text>
          </view> 
        </picker>

        <!-- 村 -->
        <picker
          v-if="item.type ==='village'"
          @change="handlePlaceChange(item.name, arguments, villageOptions)"
          :value="villageOptions.findIndex(e => e.code === formData[item.name])"
          range-key="name"
          :placeholder="item.placeholder"
          :range="villageOptions"
        >
          <view class="inner">
            <text :class="{'uni-input': true, 'placeholder': !matchName(villageOptions, formData[item.name])}">{{matchName(villageOptions, formData[item.name], item.placeholder)}}</text>
          </view> 
        </picker>

        <!-- 居住地省 -->
        <picker
          v-if="item.type ==='jz_province'"
          @change="handlePlaceChange(item.name, arguments, jz_provinceOptions, ['jz_city', 'jz_county', 'jz_street', 'jz_village'], 'jz_cityOptions', 'jz_province')"
          :value="jz_provinceOptions.findIndex(e => e.code === formData[item.name])"
          range-key="name"
          :placeholder="item.placeholder"
          :range="jz_provinceOptions"
        >
          <view class="inner">
            <text :class="{'uni-input': true, 'placeholder': !matchName(jz_provinceOptions, formData[item.name])}">{{matchName(jz_provinceOptions, formData[item.name], item.placeholder)}}</text>
          </view>  
        </picker>

        <!-- 居住地市 -->
        <picker
          v-if="item.type ==='jz_city'"
          @change="handlePlaceChange(item.name, arguments, jz_cityOptions, ['jz_county', 'jz_street', 'jz_village'], 'jz_countyOptions', 'jz_city')"
          :value="jz_cityOptions.findIndex(e => e.code === formData[item.name])"
          range-key="name"
          :placeholder="item.placeholder"
          :range="jz_cityOptions"
        >
          <view class="inner">
            <text :class="{'uni-input': true, 'placeholder': !matchName(jz_cityOptions, formData[item.name])}">{{matchName(jz_cityOptions, formData[item.name], item.placeholder)}}</text>
          </view>  
        </picker>

        <!-- 居住地县 -->
        <picker
          v-if="item.type ==='jz_county'"
          @change="handlePlaceChange(item.name, arguments, jz_countyOptions, ['jz_street', 'jz_village'], 'jz_streetOptions', 'jz_county')"
          :value="jz_countyOptions.findIndex(e => e.code === formData[item.name])"
          range-key="name"
          :placeholder="item.placeholder"
          :range="jz_countyOptions"
        >
          <view class="inner">
            <text :class="{'uni-input': true, 'placeholder': !matchName(jz_countyOptions, formData[item.name])}">{{matchName(jz_countyOptions, formData[item.name], item.placeholder)}}</text>
          </view>  
        </picker>

        <!-- 居住地街道 -->
        <picker
          v-if="item.type ==='jz_street'"
          @change="handlePlaceChange(item.name, arguments, jz_streetOptions, ['jz_village'], 'jz_villageOptions', 'jz_street')"
          :value="jz_streetOptions.findIndex(e => e.code === formData[item.name])"
          range-key="name"
          :placeholder="item.placeholder"
          :range="jz_streetOptions"
        >
          <view class="inner">
            <text :class="{'uni-input': true, 'placeholder': !matchName(jz_streetOptions, formData[item.name])}">{{matchName(jz_streetOptions, formData[item.name], item.placeholder)}}</text>
          </view> 
        </picker>

        <!-- 居住地村 -->
        <picker
          v-if="item.type ==='jz_village'"
          @change="handlePlaceChange(item.name, arguments, jz_villageOptions)"
          :value="jz_villageOptions.findIndex(e => e.code === formData[item.name])"
          range-key="name"
          :placeholder="item.placeholder"
          :range="jz_villageOptions"
        >
          <view class="inner">
            <text :class="{'uni-input': true, 'placeholder': !matchName(jz_villageOptions, formData[item.name])}">{{matchName(jz_villageOptions, formData[item.name], item.placeholder)}}</text>
          </view> 
        </picker>

      </uni-forms-item>
    </uni-forms>
    <view class="btn-row">
      <button class="primary" type="primary" :loading="btnLoading" @tap="handleSubmit">确定</button>
    </view>
  </view>
</template>
<script>
import Api from '@/api/main';

export default {
  data() {
    return {
      btnLoading: false,
      formData: {},
      regions: [],
      // 隔离信息配置项
      quarantineInfo: [
        // {
        //   // 表单控件类型
        //   type: 'input',
        //   // 控件对应的存储key
        //   name: 'username',
        //   label: '文本框',
        //   // 默认值
        //   value: '',
        //   placeholder: '请输入'
        // },
        // {
        //   type: 'textarea',
        //   name: 'username2',
        //   label: '多行文本框',
        //   value: '',
        //   placeholder: '请输入'
        // },
        // {
        //   type: 'date',
        //   name: 'username3',
        //   label: '日期选择器',
        //   value: '',
        //   placeholder: '请输入',
        //   // startDate表示从哪天开始选择
        //   startDate: '2020-12-03',
        //   // endDate表示最多选择到几号
        //   endDate: '2022-12-03'
        // },
        // {
        //   type: 'datetime',
        //   name: 'username4',
        //   label: '时间日期选择器',
        //   value: '',
        //   placeholder: '请输入'
        // },
        // {
        //   type: 'time',
        //   name: 'username5',
        //   label: '时间选择器',
        //   value: '',
        //   placeholder: '请输入'
        // },
        // {
        //   type: 'select',
        //   name: 'username6',
        //   label: '下拉选择框',
        //   value: '',
        //   options: [
        //     {
        //       label: '选项一',
        //       value: 1
        //     },
        //     {
        //       label: '选项二',
        //       value: 2
        //     }
        //   ],
        //   placeholder: '请输入'
        // },
        // {
        //   type: 'multiselect',
        //   name: 'username66',
        //   label: '多选框',
        //   value: [],
        //   options: [
        //     {
        //       label: '选项一',
        //       value: 1
        //     },
        //     {
        //       label: '选项二',
        //       value: 2
        //     }
        //   ],
        //   placeholder: '请输入'
        // },
        // {
        //   type: 'radio',
        //   name: 'username7',
        //   label: '单选框',
        //   value: '',
        //   placeholder: '请输入',
        //   options: [
        //     {
        //       label: '选项一',
        //       value: 1
        //     },
        //     {
        //       label: '选项二',
        //       value: 2
        //     }
        //   ]
        // },
        // {
        //   type: 'checkbox',
        //   name: 'username8',
        //   label: '复选框',
        //   value: [],
        //   placeholder: '请输入',
        //   options: [
        //     {
        //       label: '选项一',
        //       value: 1
        //     },
        //     {
        //       label: '选项二',
        //       value: 2
        //     }
        //   ]
        // },
        // {
        //   type: 'regions',
        //   name: 'username9',
        //   label: '省市县',
        //   // value: [省,市,县]
        //   value: ['广东省','广州市','番禺区'],
        //   placeholder: '请选择'
        // },
        // {
        //   type: 'idCard',
        //   name: 'idCard',
        //   label: '身份证号',
        //   value: '',
        //   placeholder: '请输入身份证号'
        // },
        // {
        //   type: 'birthday',
        //   name: 'birthday',
        //   label: '生日',
        //   value: '',
        //   placeholder: '请选择生日'
        // },
        // {
        //   type: 'input',
        //   name: 'age',
        //   label: '年龄',
        //   value: '',
        //   placeholder: '请输入年龄'
        // },
        // {
        //   type: 'province',
        //   name: 'province',
        //   label: '省',
        //   value: ''
        // },
        // {
        //   type: 'city',
        //   name: 'city',
        //   label: '市',
        //   value: ''
        // },
        // {
        //   type: 'county',
        //   name: 'county',
        //   label: '县',
        //   value: ''
        // },
        // {
        //   type: 'street',
        //   name: 'street',
        //   label: '街道',
        //   value: ''
        // },
        // {
        //   type: 'village',
        //   name: 'village',
        //   label: '村',
        //   value: ''
        // },
        // {
        //   name: 'custom',
        //   value: '哈哈哈'
        // },
        // {
        //   type: 'date',
        //   label: '末次暴露时间',
        //   placeholder: '请选择末次暴露时间',
        //   name: 'endOutTime',
        //   value: ''
        // },
        // {
        //   type: 'date',
        //   name: 'relieveTime',
        //   placeholder: '请选择预计解除隔离时间',
        //   label: '预计解除时间',
        //   value: ''
        // }
      ],
      genderList: [
        {
          label: '男',
          value: 1
        },
        {
          label: '女',
          value: 2
        },
        {
          label: '未知',
          value: 9
        }
      ],
      provinceOptions: [
        // {
        //   code: 11,
        //   name: '北京'
        // },
        // {
        //   code: 12,
        //   name: '天津'
        // }
      ],
      cityOptions: [],
      countyOptions: [],
      streetOptions: [],
      villageOptions: [],
      jz_provinceOptions: [],
      jz_cityOptions: [],
      jz_countyOptions: [],
      jz_streetOptions: [],
      jz_villageOptions: [],
      risk: ''
    };
  },
  computed: {
    startDate() {
      return this.getDate('start');
    },
    endDate() {
      return this.getDate();
    },
  },
  watch: {
    ['formData.endOutTime'](val) {
      if (!val) {
        return this.$set(this.formData, 'relieveTime', '')
      }
      const time = new Date(val).getTime() + 21 * 24 * 60 * 60 * 1000
      console.log('time', time);
      const relieveTime = this.getDate(null, time)
      console.log('relieveTime', relieveTime);
      this.$set(this.formData, 'relieveTime', relieveTime)
    }
  },
  methods: {
    handleMultiselectChange(name, args) {
      console.log('handleMultiselectChange', name, args[0]);
      this.$set(this.formData, name, args[0])
    },
    handleListChange($event, name, list, key) {
      const index = Number($event.detail.value);
      key ? this.binddata(name, list[index][key]) : this.binddata(name, list[index])
    },
    handleBirthdayChange(name, [val]) {
      const { value } = val.detail
      this.$set(this.formData, name, value)
      // 设置年龄
      if (value) {
        this.$set(this.formData, 'age', new Date().getFullYear() - new Date(value).getFullYear())
      }
    },
    handleIdCardBlur(name, [val]) {
      const { value } = val.detail
      this.$set(this.formData, name, value)
      console.log('value', value);
      if (!this.formData.birthday && (value.length === 18 || value.length === 15)) {
        const birthday = this.getBirthdayFromIdCard(value)
        const gender = this.getGenderfromIdCard(value)
        const age = new Date().getFullYear() - new Date(birthday).getFullYear()
        // 出生日期
        this.$set(this.formData, 'birthday', birthday);
        // 年龄
        this.$set(this.formData, 'age', age)
        // 性别
        this.$set(this.formData, 'gender', gender)
        console.log('idCard', value);
        console.log('birthday', birthday);
        console.log('age', age);
        console.log('gender', gender);
      }
    },
    async handlePlaceChange(name, [val], options, reset = [], next, type = 'province') {
      console.log(arguments);
      const { value: index } = val.detail
      const value = options[index]
      this.$set(this.formData, name, value.code)
      
      // 重置
      reset.forEach(name => {
        this.$set(this.formData, name, '')
      })

      // 查询下级标签
      if (this[next]) {
        this[next] = await this.getRegions({ ...value, type }) || []
        console.log(next, this[next]);
      }
    },
    getBirthdayFromIdCard(idCard) {
      let birthday = "";
      if(idCard != null && idCard != ""){
        if(idCard.length == 15){
          birthday = "19"+idCard.substr(6,6);
        } else if(idCard.length == 18){
          birthday = idCard.substr(6,8);
        }
      
        birthday = birthday.replace(/(.{4})(.{2})/,"$1-$2-");
      }
      
      return birthday;
    },
    getGenderfromIdCard(idCard) {
      if (parseInt(idCard.substr(16,1)) % 2 == 1) {
        return 1
      }
      return 2
    },
    getDate(type, time = Date.now()) {
      const date = new Date(time);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      if (type === 'start') {
        year = year - 60;
      } else if (type === 'end') {
        year = year + 2;
      }
      month = month > 9 ? month : '0' + month;
      day = day > 9 ? day : '0' + day;
      return `${year}-${month}-${day}`;
    },
    handleGetRegion(name, region) {
      this.formData[name] = region.map(item => item.name)
      console.log('region', name, region);
    },
    handleSubmit() {
      this.$refs.form.submit();
    },
    submit(event) {
      const { errors, value } = event.detail;
      console.log('event', event);
      if (errors) return;
      this.save(value);
    },
    matchLabel(list = [], value, placeholder = '') {  
      if (!list || !list.length || !value) {
        return placeholder
      }

      const target = list.find(item => item.value === value)
      return target ? target.label : placeholder
    },
    matchName(list = [], code, placeholder = '') {
      if (!list || !list.length) {
        return placeholder
      }
      const target = list.find(item => item.code === code)
      return target ? target.name : placeholder
    },
    radioChange(...val) {
      console.log('val', val);
    },
    // 存储
    async save(data) {
      console.log('save', data, this.formData);
      if (!this.quarantineInfo || !this.quarantineInfo.length) {
        return
      }
      const res = await this.$http.post(Api.addRiskInfo, this.formData);
      if (res) {
        this.$toast('申请成功');
        setTimeout(() => {
          uni.navigateBack();
        }, 200);
      }
    },
    // 查询隔离信息配置项
    async getQuarantineInfo(risk) {
      const res = await this.$http.post(Api.getQuarantineInfo, { risk });
      if (res) {
        this.quarantineInfo = res;
        console.log('quarantineInfo', this.quarantineInfo);
        // 初始化对象
        this.formData = this.quarantineInfo.reduce((pre, item)=> {
          return Object.assign(pre, {
            [item.name]: item.value
          })
        }, {})
        console.log('formData', this.formData);
      }
    },
    // 查询城市信息
    async getRegions({ code = 0, name, type = 'province' } = {}) {
      const res = await this.$http.post(Api.getRegions, { code, name, [type]: code })
      return res || []
    }
  },
  async onLoad(obj) {
    uni.showLoading({
      title: '加载中...'
    });
    // this.formData = this.quarantineInfo.reduce((pre, item)=> {
    //   return Object.assign(pre, {
    //     [item.name]: item.value
    //   })
    // }, {})
    await this.getQuarantineInfo(obj.risk)
    this.provinceOptions = this.jz_provinceOptions = await this.getRegions() || []
    uni.hideLoading();
  }
};
</script>
<style lang="scss">
.add-risk {
  width: 100%;
  padding: 0 40rpx;
  input {
    width: 100%;
    text-align: right;
    font-size: 14px;
  }
  picker {
    justify-content: flex-end;
  }
  radio-group {
    width: 100%;
    text-align: right;
  }
  ld-select {
    text-align: right;
  }
}
textarea {
  padding-top: 20rpx;
  width: 100%;
}
.radio,
.checkbox {
  margin-right: 20rpx;
}
label {
  display: inline-flex;
  align-items: center;
  text {
    font-size: 28rpx;
  }
}
.inner {
  width: 100%;
  height: 100%;
  text {
    text-align: right;
    font-size: 14px;
  }
}
picker {
  .inner > .placeholder {
    // font-size: 34rpx;
    color: $uni-text-color-placeholder;
  }
}
ld-select {
  width: 100%;
}
</style>